package com.wch.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.org.apache.regexp.internal.RE;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {  //设置过滤器类型
        return "pre";   //前置过滤器
    }

    @Override
    public int filterOrder() {
        return 0;  //设置优先级，数字越大，优先级越低
    }

    @Override
    public boolean shouldFilter() {
        return true;  //过滤器开关，true表示开启
    }

    /**
     * 处理逻辑解析：
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {   //过滤器的具体实现逻辑
        System.out.println("Zuul过滤器");

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        if("OPTIONS".equals(request.getMethod())){
            return null;
        }

        String url = request.getRequestURL().toString();
        if (url.indexOf("/admin/login")>0){
            System.out.println("登录页面"+url);
            return  null;
        }

        String authHeader = request.getHeader("Authorization");   //获取头信息
        if (null != authHeader && authHeader.startsWith("Bearer ")){
            String token = authHeader.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if (null != claims){
                if("admin".equals(claims.get("roles"))){
                    requestContext.addZuulRequestHeader("Authorization",authHeader);
                    System.out.println("token验证通过，添加了头信息："+authHeader);
                    return null;
                }
            }
        }

        requestContext.setSendZuulResponse(false);  //终止运行    令zuul过滤该请求，不对其进行路由
        requestContext.setResponseStatusCode(401);  //http状态码   设置其返回的错误码
        requestContext.setResponseBody("无权访问");

        requestContext.getResponse().setContentType("text/html;charset=UTF-8");
        return null;
    }
}
